package cn.edu.nit.sys.service.impl;

import cn.edu.nit.sys.dto.UserDTO;
import cn.edu.nit.sys.entity.User;
import cn.edu.nit.sys.mapper.UserMapper;
import cn.edu.nit.sys.service.UserService;
import cn.edu.nit.sys.socket.MessageSocketHandler;
import cn.edu.nit.sys.utils.R;
import cn.edu.nit.sys.utils.Utils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MessageSocketHandler messageSocketHandler;

    @Override
    public R getList(Page<UserDTO> page, String name, String role) {
        Page<UserDTO> userList = baseMapper.getUserList(page, name, role, "");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", userList.getTotal());
        jsonObject.put("list", userList.getRecords());
        return R.ok(jsonObject);
    }

    @Override
    public R updateUserPhone(Map<String, String> params) {
        String id = params.get("id");
        String phone = params.get("phone");
        String code = params.get("code");
        String role = params.get("roleId");
        if(!code.equals(redisTemplate.opsForValue().get(phone))) {
            return R.error("验证码错误");
        }
        // 验证通过删除验证码缓存
        redisTemplate.opsForValue().set(phone, "", 5, TimeUnit.MILLISECONDS);
        int rs = 0;
        if("14".equals(role)) { // 学生
            rs = baseMapper.updateStudentPhone(id, phone);
        }else if("10".equals(role)) { // 老师
            rs = baseMapper.updateTeacherPhone(id, phone);
        }
        return rs > 0 ? R.ok("修改成功") : R.error("修改失败");
    }

    @Override
    public R updatePassword(Map<String, String> params) {
        String account = params.get("account");
        String password = params.get("password");
        baseMapper.updatePassword(account, password);
        return R.ok("修改成功");
    }

    @Override
    @Transactional
    public R updateInfo(Map<String, String> params) {
        String id = params.get("id");
        String nickname = params.get("nickname");
        String email = params.get("email");
        String avatar = params.get("avatar");
        String exist = baseMapper.isExist(nickname);
        if(StringUtils.isNotEmpty(exist)) {
            return R.error("昵称已被使用");
        }
        baseMapper.updateInfo(id, avatar, nickname);
        if("10".equals(getRoleId(id))) {    // 老师
            baseMapper.updateStudentEmail(id, email);
        }else if("14".equals(getRoleId(id))) {  // 学生
            baseMapper.updateTeacherEmail(id, email);
        }
        return R.ok("修改成功");
    }

    private String getRoleId(String id) {
        return baseMapper.getRoleId(id);
    }

    @Override
    public R baseData(String id) {
        Map<String, Integer> rs = baseMapper.countData(id);
        return R.ok(rs);
    }

    @Override
    public R checkFans(String uid, String id) {
        String rs = baseMapper.checkFans(uid, id);
        return R.ok(StringUtils.isNotEmpty(rs));
    }

    @Override
    @Transactional
    public R updateFans(String uid, String id) {
        String primaryId = UUID.randomUUID().toString().replaceAll("\\-", "");
        baseMapper.updateFans(primaryId, uid, id);
        messageSocketHandler.sendMessage(id, uid, "0", "", "");
        return R.ok("");
    }

    @Override
    public R getClazzUser(String id) {
        List<Map<String, String>> list = baseMapper.getClazzUser(id);
        List<Map<String, String>> data = new ArrayList<>();
        for(Map<String, String> stu : list) {
            String letter = Utils.getStrFirstLetter(stu.get("name").substring(0, 1));
            stu.put("char", letter.toUpperCase());
            data.add(stu);
        }
        return R.ok(data);
    }

    @Override
    public R getAFUserList(Page<Map<String, String>> page, String id, String type) {
        Page<Map<String, String>> list = null;
        if("0".equals(type)) {
            list = baseMapper.getAttentionUser(page, id);
        }else if("1".equals(type)) {
            list = baseMapper.getFansUser(page, id);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", list.getTotal());
        jsonObject.put("list", list.getRecords());
        return R.ok(jsonObject);
    }
}
